/*
 * @Author: Turump 
 * @Date: 2021-03-26 09:50:20 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-09-17 11:22:53
 * !!!SoundHelper现在只能播放TFrameRes下的音效文件
 */

import SingletonBase from "./SingleTonBase";

export default class SoundHelper extends SingletonBase {
    private bgmAudioClip: cc.AudioClip = null;
    private bgmID = -1;

    public playBGM(ac: cc.AudioClip, loop = true) {
        if (this.bgmAudioClip == ac && cc.audioEngine.isMusicPlaying()) {
            console.log("SoundHelper playBGM repeat:" + cc.audioEngine.isMusicPlaying());
            return;
        } 
        this.bgmAudioClip && this.bgmAudioClip.decRef();
        cc.audioEngine.stopMusic();
        this.bgmID = cc.audioEngine.playMusic(ac, loop);
        this.bgmAudioClip = ac;
        this.bgmAudioClip.addRef();
        cc.audioEngine.setFinishCallback(this.bgmID, () => {
            console.log("SoundHelper 音乐停止:", cc.audioEngine.isMusicPlaying())
            if(cc.audioEngine.isMusicPlaying() == false) {
                this.playBGM(this.bgmAudioClip);
            }
        })
    }

    static playAudio(bundleName:string, path:string) {
        if(path.indexOf('sound/') == -1) {
            path = 'sound/' + path;
        }
        cc.assetManager.loadBundle(bundleName, (err: Error, bundle: cc.AssetManager.Bundle) => {
            if (bundle == null)
                return cc.error("Error:", err.message)
            bundle.load(path, cc.AudioClip, (err: Error, ac: cc.AudioClip) => {
                if (err)
                    return cc.log("Error:", err.message);
                cc.audioEngine.playEffect(ac, false);
            })
        });
    }
}
